<div id="storegoodslist">
    <el-container>
        <el-main>
            <!-- 页面标题和标签页 -->
            <div class="page-header">
                <h2 class="page-title">商品清单</h2>
                <div class="tabs">
                    <div
                        class="tab-item"
                        :class="{ active: activeTab === 'onSale' }"
                        @click="activeTab = 'onSale'"
                    >
                        上架中 (@{{ onSaleCount }})
                    </div>
                    <div
                        class="tab-item"
                        :class="{ active: activeTab === 'warehouse' }"
                        @click="activeTab = 'warehouse'"
                    >
                        仓库中 (@{{ warehouseCount }})
                    </div>
                </div>
            </div>

            <!-- 搜索和筛选区域 -->
            <el-card class="mb-4">
                <div slot="header">
                    <span><i class="el-icon-search"></i> 搜索筛选</span>
                </div>
                <el-form :model="searchForm" class="search-form" :inline="true">
                    <!-- 售罄筛选（仅在仓库中显示） -->
                    <el-form-item v-if="activeTab === 'warehouse'" label="">
                        <el-select
                            v-model="searchForm.isSoldOut"
                            placeholder="请选择售罄中商品"
                            clearable
                            @change="handleSearch"
                            style="width: 200px;"
                        >
                            <el-option label="售罄中商品" :value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品分类">
                        <el-select
                            v-model="searchForm.categoryId1"
                            placeholder="一级分类"
                            clearable
                            style="width: 150px;"
                        >
                            <el-option
                                v-for="item in category1List"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                        <el-select
                            v-model="searchForm.categoryId2"
                            placeholder="二级分类"
                            clearable
                            style="width: 150px; margin-left: 10px;"
                        >
                            <el-option
                                v-for="item in category2List"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品名称">
                        <el-input
                            v-model="searchForm.title"
                            placeholder="请输入商品名称"
                            clearable
                            style="width: 200px;"
                        />
                    </el-form-item>
                    <el-form-item label="门店名称">
                        <el-input
                            v-model="searchForm.store_name"
                            placeholder="请输入门店名称"
                            clearable
                            style="width: 200px;"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <!-- 批量操作区域 -->
            <el-card class="mb-4">
                <div class="batch-actions">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <el-button
                        type="default"
                        :disabled="selectedItems.length === 0"
                        @click="handleBatchOnSale"
                    >
                        批量上架
                    </el-button>
                    <el-button
                        type="default"
                        :disabled="selectedItems.length === 0"
                        @click="handleBatchOffSale"
                    >
                        批量下架
                    </el-button>
                    <el-button
                        type="default"
                        :disabled="selectedItems.length === 0"
                        @click="handleBatchModifyCategory"
                    >
                        批量修改分类
                    </el-button>
                </div>
            </el-card>

            <!-- 商品列表表格 -->
            <el-card>
                <div slot="header">
                    <span><i class="el-icon-goods"></i> 商品清单</span>
                    <span class="text-muted ml-2">共 @{{ pagination.total }} 个商品</span>
                </div>
                
                <el-table
                    ref="productTable"
                    :data="productList"
                    v-loading="loading"
                    @selection-change="handleSelectionChange"
                    stripe
                    style="width: 100%"
                >
                    <el-table-column type="selection" width="55" ></el-table-column>
                    <el-table-column prop="id" label="商品ID" width="80" ></el-table-column>
                    <el-table-column prop="display_order" label="排序" width="80" ></el-table-column>
                    <el-table-column label="商品图片" width="100">
                        <template slot-scope="scope">
                            <el-image
                                :src="scope.row.thumb || '/images/default-goods.png'"
                                :preview-src-list="[scope.row.thumb]"
                                class="product-thumb"
                                fit="cover"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="title"
                        label="商品名称"
                        min-width="200"
                        show-overflow-tooltip
                    >
                    </el-table-column>
                    <el-table-column label="价格" width="120">
                        <template slot-scope="scope">
                            <span class="price">¥@{{ scope.row.price }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存" width="120">
                        <template slot-scope="scope">
                            <span>@{{ scope.row.stock }}</span>
                            <el-button
                                type="text"
                                size="mini"
                                @click="handleEditStock(scope.row)"
                            >
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_sales" label="销量" width="100" ></el-table-column>
                    <el-table-column label="所属门店" width="150">
                        <template slot-scope="scope">
                            <span>@{{ scope.row.store_name || '-' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="上下架状态" width="120">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="0"
                                @change="handleStatusChange(scope.row)"
                            />
                            <span class="status-text">@{{ scope.row.status ? "上架" : "下架" }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否推荐" width="120">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.is_recommand"
                                :active-value="1"
                                :inactive-value="0"
                                @change="handleRecommandChange(scope.row)"
                            />
                            <span class="status-text">@{{ scope.row.is_recommand ? "推荐" : "不推荐" }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" size="mini" @click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-wrapper mt-3" v-if="pagination.total > 0">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.page"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.limit"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total"
                    />
                </div>
            </el-card>

            <!-- 编辑库存对话框 -->
            <el-dialog
                title="编辑库存"
                :visible.sync="stockDialogVisible"
                width="400px"
            >
                <el-form :model="stockForm" label-width="80px">
                    <el-form-item label="当前库存">
                        <el-input-number v-model="stockForm.stock" :min="0" style="width: 100%;" />
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="stockDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveStock">确定</el-button>
                </div>
            </el-dialog>

            <!-- 批量修改分类对话框 -->
            <el-dialog
                title="批量修改分类"
                :visible.sync="categoryDialogVisible"
                width="500px"
            >
                <el-form :model="categoryForm" label-width="100px">
                    <el-form-item label="一级分类">
                        <el-select
                            v-model="categoryForm.categoryId1"
                            placeholder="请选择一级分类"
                            style="width: 100%;"
                            @change="onCategory1Change"
                        >
                            <el-option
                                v-for="item in category1List"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="二级分类">
                        <el-select
                            v-model="categoryForm.categoryId2"
                            placeholder="请选择二级分类"
                            style="width: 100%;"
                        >
                            <el-option
                                v-for="item in category2ListForDialog"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="categoryDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveCategory">确定</el-button>
                </div>
            </el-dialog>
        </el-main>
    </el-container>
</div>

<script>
new Vue({
    el: '#storegoodslist',
    data() {
        return {
            activeTab: 'onSale',
            loading: false,
            selectAll: false,
            selectedItems: [],
            productList: [],
            onSaleCount: 0,
            warehouseCount: 0,

            // 搜索表单
            searchForm: {
                title: '',
                store_name: '',
                categoryId1: '',
                categoryId2: '',
                status: 1,
                isSoldOut: ''
            },

            // 分页
            pagination: {
                page: 1,
                limit: 10,
                total: 0
            },

            // 分类数据
            category1List: [],
            category2List: [],
            category2ListForDialog: [],

            // 编辑库存对话框
            stockDialogVisible: false,
            stockForm: {
                id: null,
                stock: 0
            },

            // 批量修改分类对话框
            categoryDialogVisible: false,
            categoryForm: {
                categoryId1: '',
                categoryId2: ''
            }
        }
    },
    mounted() {
        this.loadProductList();
        this.loadCategories();
    },
    watch: {
        // 监听一级分类变化，加载对应的二级分类
        'searchForm.categoryId1'(newVal) {
            this.searchForm.categoryId2 = '';
            if (newVal) {
                this.loadCategory2List(newVal);
            } else {
                this.category2List = [];
            }
        },
        // 监听批量修改分类弹框中的一级分类变化
        'categoryForm.categoryId1'(newVal) {
            this.categoryForm.categoryId2 = '';
            if (newVal) {
                this.loadCategory2ListForDialog(newVal);
            } else {
                this.category2ListForDialog = [];
            }
        },
        // 监听标签页切换
        activeTab(newVal) {
            this.searchForm.status = newVal === 'onSale' ? 1 : 0;
            this.searchForm.isSoldOut = '';
            this.pagination.page = 1;
            this.loadProductList();
        }
    },
    methods: {
        // 加载商品列表
        async loadProductList() {
            this.loading = true;
            try {
                const params = {
                    page: this.pagination.page,
                    limit: this.pagination.limit,
                    title: this.searchForm.title || '',
                    store_name: this.searchForm.store_name || '',
                    status: this.searchForm.status
                };

                // 优先使用二级分类，如果没有二级分类则使用一级分类
                if (this.searchForm.categoryId2) {
                    params.categoryId2 = this.searchForm.categoryId2;
                } else if (this.searchForm.categoryId1) {
                    params.categoryId1 = this.searchForm.categoryId1;
                }

                // 如果选择了售罄中商品筛选
                if (this.searchForm.isSoldOut === 1) {
                    params.isSoldOut = 1;
                }

                // 过滤空值
                Object.keys(params).forEach(key => {
                    if (params[key] === '' || params[key] === null || params[key] === undefined) {
                        delete params[key];
                    }
                });

                const response = await window.api.post('/admin/store-goods/list', params);
                
                if (response && response.result === 1) {
                    this.productList = response.data.list || [];
                    this.pagination.total = response.data.total || 0;

                    // 使用后端返回的统计数据
                    if (response.data.stats) {
                        this.onSaleCount = response.data.stats.online_count || 0;
                        this.warehouseCount = response.data.stats.offline_count || 0;
                    }
                } else {
                    this.$message.error(response.msg || '加载商品列表失败');
                }
            } catch (error) {
                console.error('loadProductList error', error);
                this.$message.error('加载商品列表失败');
            } finally {
                this.loading = false;
            }
        },

        // 加载一级分类数据
        async loadCategories() {
            try {
                // 调用门店端的分类接口，不传organid表示查询所有门店的分类
                const response = await window.api.post('/api/store/goods/getCategories', {
                    param: { level: 1 },
                    organid: null // 不传organid，查询所有门店的分类
                });
                if (response && response.result === 1) {
                    this.category1List = response.data.list || [];
                } else {
                    this.$message.error(response.msg || '加载分类失败');
                }
            } catch (error) {
                console.error('加载分类失败', error);
                this.$message.error('加载分类失败');
            }
        },

        // 加载二级分类数据
        async loadCategory2List(parentId) {
            try {
                const response = await window.api.post('/api/store/goods/getCategories', {
                    param: { level: 2, parent_id: parentId },
                    organid: null
                });
                if (response && response.result === 1) {
                    this.category2List = response.data.list || [];
                } else {
                    this.$message.error(response.msg || '加载二级分类失败');
                }
            } catch (error) {
                console.error('加载二级分类失败', error);
                this.$message.error('加载二级分类失败');
            }
        },

        // 加载弹框中的二级分类数据
        async loadCategory2ListForDialog(parentId) {
            try {
                const response = await window.api.post('/api/store/goods/getCategories', {
                    param: { level: 2, parent_id: parentId },
                    organid: null
                });
                if (response && response.result === 1) {
                    this.category2ListForDialog = response.data.list || [];
                } else {
                    this.$message.error(response.msg || '加载二级分类失败');
                }
            } catch (error) {
                console.error('加载二级分类失败', error);
                this.$message.error('加载二级分类失败');
            }
        },

        // 一级分类变化（弹框中）
        onCategory1Change() {
            this.categoryForm.categoryId2 = '';
            if (this.categoryForm.categoryId1) {
                this.loadCategory2ListForDialog(this.categoryForm.categoryId1);
            } else {
                this.category2ListForDialog = [];
            }
        },

        // 搜索
        handleSearch() {
            this.pagination.page = 1;
            this.loadProductList();
        },

        // 重置搜索
        handleReset() {
            this.searchForm = {
                title: '',
                store_name: '',
                categoryId1: '',
                categoryId2: '',
                status: this.activeTab === 'onSale' ? 1 : 0,
                isSoldOut: ''
            };
            this.category2List = [];
            this.handleSearch();
        },

        // 全选
        handleSelectAll(val) {
            if (val) {
                this.productList.forEach(row => {
                    this.$refs.productTable.toggleRowSelection(row, true);
                });
            } else {
                this.$refs.productTable.clearSelection();
            }
        },

        // 选择变化
        handleSelectionChange(selection) {
            this.selectedItems = selection;
            this.selectAll = selection.length > 0 && selection.length === this.productList.length;
        },

        // 批量上架
        async handleBatchOnSale() {
            if (this.selectedItems.length === 0) {
                this.$message.warning('请选择要上架的商品');
                return;
            }

            try {
                const ids = this.selectedItems.map(item => item.id);
                const response = await window.api.post('/admin/store-goods/batch-update', {
                    ids: ids,
                    status: 1
                });
                
                if (response && response.result === 1) {
                    this.$message.success('批量上架成功');
                    this.loadProductList();
                } else {
                    this.$message.error(response.msg || '批量上架失败');
                }
            } catch (error) {
                console.error('批量上架失败', error);
                this.$message.error('批量上架失败');
            }
        },

        // 批量下架
        async handleBatchOffSale() {
            if (this.selectedItems.length === 0) {
                this.$message.warning('请选择要下架的商品');
                return;
            }

            try {
                const ids = this.selectedItems.map(item => item.id);
                const response = await window.api.post('/admin/store-goods/batch-update', {
                    ids: ids,
                    status: 0
                });
                
                if (response && response.result === 1) {
                    this.$message.success('批量下架成功');
                    this.loadProductList();
                } else {
                    this.$message.error(response.msg || '批量下架失败');
                }
            } catch (error) {
                console.error('批量下架失败', error);
                this.$message.error('批量下架失败');
            }
        },

        // 批量修改分类
        handleBatchModifyCategory() {
            if (this.selectedItems.length === 0) {
                this.$message.warning('请选择要修改分类的商品');
                return;
            }
            this.categoryForm = {
                categoryId1: '',
                categoryId2: ''
            };
            this.category2ListForDialog = [];
            this.categoryDialogVisible = true;
        },

        // 保存分类修改
        async handleSaveCategory() {
            try {
                const ids = this.selectedItems.map(item => item.id);
                const params = {
                    ids: ids
                };
                
                if (this.categoryForm.categoryId1) {
                    params.category_id_1 = this.categoryForm.categoryId1;
                }
                if (this.categoryForm.categoryId2) {
                    params.category_id_2 = this.categoryForm.categoryId2;
                }
                
                const response = await window.api.post('/admin/store-goods/batch-update', params);
                
                if (response && response.result === 1) {
                    this.$message.success('批量修改分类成功');
                    this.categoryDialogVisible = false;
                    this.loadProductList();
                } else {
                    this.$message.error(response.msg || '批量修改分类失败');
                }
            } catch (error) {
                console.error('批量修改分类失败', error);
                this.$message.error('批量修改分类失败');
            }
        },

        // 编辑库存
        handleEditStock(row) {
            this.stockForm = {
                id: row.id,
                stock: row.stock
            };
            this.stockDialogVisible = true;
        },

        // 保存库存
        async handleSaveStock() {
            try {
                const response = await window.api.post('/admin/store-goods/update', {
                    goods_id: this.stockForm.id,
                    stock: this.stockForm.stock
                });
                
                if (response && response.result === 1) {
                    this.$message.success('库存更新成功');
                    this.stockDialogVisible = false;
                    this.loadProductList();
                } else {
                    this.$message.error(response.msg || '库存更新失败');
                }
            } catch (error) {
                console.error('库存更新失败', error);
                this.$message.error('库存更新失败');
            }
        },

        // 状态变化
        async handleStatusChange(row) {
            try {
                const response = await window.api.post('/admin/store-goods/update', {
                    goods_id: row.id,
                    status: row.status
                });
                
                if (response && response.result === 1) {
                    this.$message.success('状态更新成功');
                    this.loadProductList(); // 刷新统计数据
                } else {
                    this.$message.error(response.msg || '状态更新失败');
                    // 恢复原状态
                    row.status = row.status === 1 ? 0 : 1;
                }
            } catch (error) {
                console.error('状态更新失败', error);
                this.$message.error('状态更新失败');
                // 恢复原状态
                row.status = row.status === 1 ? 0 : 1;
            }
        },

        // 推荐状态变化
        async handleRecommandChange(row) {
            try {
                const response = await window.api.post('/admin/store-goods/update', {
                    goods_id: row.id,
                    is_recommand: row.is_recommand
                });
                
                if (response && response.result === 1) {
                    this.$message.success('推荐状态更新成功');
                } else {
                    this.$message.error(response.msg || '推荐状态更新失败');
                    // 恢复原状态
                    row.is_recommand = row.is_recommand === 1 ? 0 : 1;
                }
            } catch (error) {
                console.error('推荐状态更新失败', error);
                this.$message.error('推荐状态更新失败');
                // 恢复原状态
                row.is_recommand = row.is_recommand === 1 ? 0 : 1;
            }
        },

        // 编辑商品
        handleEdit(row) {
            window.location.href = '/admin/store-goods/detail?id=' + row.id;
        },

        // 分页大小变化
        handleSizeChange(val) {
            this.pagination.limit = val;
            this.pagination.page = 1;
            this.loadProductList();
        },

        // 当前页变化
        handleCurrentChange(val) {
            this.pagination.page = val;
            this.loadProductList();
        }
    }
});
</script>

<style scoped>
.page-header {
    margin-bottom: 20px;
}

.page-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 16px;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
}

.tab-item {
    padding: 12px 24px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    color: #606266;
}

.tab-item.active {
    color: #409eff;
    border-bottom-color: #409eff;
}

.batch-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.product-thumb {
    width: 60px;
    height: 60px;
    border-radius: 4px;
}

.price {
    color: #f56c6c;
    font-weight: bold;
}

.status-text {
    margin-left: 8px;
    font-size: 12px;
}

.pagination-wrapper {
    margin-top: 20px;
    text-align: right;
}

.text-muted {
    color: #909399;
    font-size: 14px;
}

.ml-2 {
    margin-left: 8px;
}

.mt-3 {
    margin-top: 16px;
}

.mb-4 {
    margin-bottom: 16px;
}
</style>
